import WxValidate from '../../lib/WxValidate.js'
const app = getApp()


Page({



  onLoad:function(option){
    // 初始化验证方法
    this.initValidate()
    console.log(option)
    console.log(wx.getStorageSync('user').openid)

    this.setData({
      deviceId:option.deviceId+"",
    });
    // this.setData({
    //   deviceId:'7C:9E:BD:04:95:E6'
    // })
    this.openBluetoothAdapter()
  },

  data: {
    chePaiHao:"",
    wiffZhangHao:"",
    wiffMiMa:"",
    cuoWuChePaiHao:false,
  

    openid:wx.getStorageSync('user').openid,
    
    
    
    sao_miao_loading:false,//开始扫描”按钮是否出现等待
    input_fa_song_value:"",//发送intpu里的值
    //蓝牙相关
    connected:false,//蓝牙是否连接
    canWrite:false,
    chs: [],
    deviceId:"",
    name:"",
    serviceId :"",
    characteristicId:""
    //蓝牙相关结束
  },

  mqttSend:()=>{
    wx.navigateTo({
      url: '/pages/index/index',
    })
  },

  //提交处理函数
  formSubmit: function (e) {

        
    let issueInfo = e.detail.value
    
    //校验表单
    if (!this.WxValidate.checkForm(issueInfo)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }

    // wx.showLoading({
    //   title: '加载中',
    //   mask: true
    // })

    //let val='BW'+issueInfo.wiffZhangHao+","+issueInfo.wiffMiMa
    let val= issueInfo.wiffZhangHao+","+issueInfo.wiffMiMa

    this.setData({
      chePaiHao:issueInfo.chePaiHao
    })





    function writeCallBack(res){
      console.log(JSON.stringify(res))
    }
    this.writeBLECharacteristicValue(val)

  },

  //报错
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },

  //验证函数
  initValidate() {
    const rules = {
      chePaiHao: {
        required: true,
        maxlength: 128
      },
      wiffZhangHao: {
        required: true,
        maxlength: 128
      },
      wiffMiMa: {
        required: true,
        maxlength: 128
      },
     
    }
    const messages = {
      chePaiHao: {
        required: '请输入车牌号',
        minlength: '最多只能输入128个字符'
      },
      wiffZhangHao: {
        required: '请输入wiff账号',
        minlength: '最多只能输入128个字符'
      },
      wiffMiMa: {
        required: '请输入wiff密码',
        minlength: '最多只能输入128个字符'
      },
      
    }
    this.WxValidate = new WxValidate(rules, messages)
  },


  openBluetoothAdapter() {
    let that=this;
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        //this.startBluetoothDevicesDiscovery()
          this.createBLEConnection();
        that.setData({
            connected:true
          })
      },
      complete:(res)=>{
        console.log("openBluetoothAdapter complete:"+res)
      },
      fail: (res) => {
        console.log(JSON.stringify(res))
        wx.showModal({
          title:"请开启蓝牙",
          showCancel:false
        })
        that.setData({
          connected:false
        })
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            //console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              //this.createBLEConnection();
            }
          })
        }
      }
    })
  },

  createBLEConnection() {

  let that=this;

    const deviceId = this.data.deviceId
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        that.setData({
          connected: true,
        })
        this.getBLEDeviceServices(deviceId)
      },
      complete:(res)=>{
        console.log("createBLEConnection complete:"+res)
        if(res.errCode===-1){
          that.setData({
            connected: true,
          })
          this.getBLEDeviceServices(deviceId)
        }
      },
    })
  },

  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },

  getBLEDeviceCharacteristics(deviceId, serviceId) {
    let that=this;
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            that.setData({
              canWrite: true
            })
            that.setData({
              deviceId :deviceId,
              serviceId : serviceId,
              characteristicId : item.uuid
            })



            //this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {

      let str=bufferToString(characteristic.value)

      // wx.showModal({
      //   title:str,
      //   showCancel:false
      // })

      if(str==="SSSS"){


        let that=this
        //let sql="update qi_che_che_liang set  openid='"+wx.getStorageSync('user').openid+"' where role_name='"+that.data.chePaiHao+"'"
        let sql="select role_id from qi_che_che_liang where role_name='"+that.data.chePaiHao+"'";
        wx.request({
          url: app.globalData.urlGlobal+'/commonZwl/getZwl', //url
          method: 'GET', //请求方式
          header: {
            'Content-Type': 'application/json',
          },
          data: {
            sql: sql,  //参数
          },
          success: function(res) {
            let data=res.data.rtn;
            if(data.length===0){
              wx.showModal({
                title:'错误车牌号，绑定失败',
                showCancel:false
              })
            }
            if(data.length>0){
              sql="update qi_che_che_liang set deviceid='"+that.data.deviceId+"' ,  openid='"+wx.getStorageSync('user').openid+"' where role_name='"+that.data.chePaiHao+"'"
              wx.request({
                url: app.globalData.urlGlobal+'/commonZwl/getZwl', //url
                method: 'GET', //请求方式
                header: {
                  'Content-Type': 'application/json',
                },
                data: {
                  sql: sql,  //参数
                },
                success: function(res) {
                  let data=res.data.rtn;
                  // if(data.length>=0){
                    wx.showModal({
                      title:"绑定成功",
                      showCancel:false,
                      success(res) {
                        if(res.confirm){
                          wx.navigateTo({
                            url: '/pages/index/index',
                          })
                        }
                      }
                    })
                  // }

                },
                fail: function() {
                  console.log("请求数据失败");
                },
                complete: function() {
                  // complete
                }
              })
            }
          },
          fail: function() {
            console.log("请求数据失败");
          },
          complete: function() {
            // complete
          }
        })









      }

      if(str==="EEEE")
      {
        wx.showModal({
          title:"wiff链接失败，请重试",
          showCancel:false
        })
      }

      /*
      wx.showModal({
        title:str,
        showCancel:false
      })
      */

      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
        
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
      console.log(data)
      //this.showModal(JSON.stringify(data))
    })
  },

  writeBLECharacteristicValue(value) {
    if(!this.data.connected){
      wx.showModal({
        title: '蓝牙连接中',
        showCancel:false
      })
    }
    //value="~!AABW"+value+"\n"
    value="~!AA"+value+"\n"

    for(let i=0;i<value.length;i=i+10){
      let s=value.substring(i,i+10)
      this.writeBlue(s)
    }

  },
  writeBlue(val){
    let that=this;
    let command=val;
    var buf = new ArrayBuffer(command.length); // 
    var bufView = new Uint8Array(buf);
    for (var i=0, strLen=command.length; i<strLen; i++) {
      bufView[i] = command.charCodeAt(i);
    }
    let str=bufferToString(buf)
    console.log(str)
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.characteristicId,
      value: buf,
      /*
      success:(res)=>{
        wx.showModal({
          title:JSON.stringify(res),
          showCancel:false
        })
      }
       */
    })


     //this.openBluetoothAdapter();
    //var command=event.currentTarget.dataset.command
    

    /*
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, Math.random() * 255 | 0)
    */

    //字符串转为ArrayBuffer对象，参数为字符串
    //var str=this.input_fa_song_value;
    //console.log(str);


  }

})

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
function bufferToString(buffer){
  return String.fromCharCode.apply(null, new Uint8Array(buffer))
}